﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace MarioArena.Multiplayer
{
    class UDPConnection
    {
        public bool IsConnected { get; set; }
        public int LocalPort { get; set; }

        private UDPSender mUdpSender;
        private UDPReceiver mUdpReceiver;
        private Thread mSenderThread;
        private Thread mReceiverThread;
        private UdpClient mUdpClient;

        #region Singleton
        private static UDPConnection instance = new UDPConnection();
        public static UDPConnection Instance
        {
            get
            {
                return instance;
            }
        }
        private UDPConnection() 
        { 
        }
        #endregion

        public void Initialize()
        {
            string ip = Settings.IPAddress;
            int port = Settings.Port;
            mUdpClient = new UdpClient();
            IPAddress serverIp = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(serverIp, port);

            IPEndPoint localendpoint = new IPEndPoint(IPAddress.Any, 0);
            mUdpClient.AllowNatTraversal(true);
            mUdpClient.Client.Bind(localendpoint);
            this.LocalPort = ((IPEndPoint)mUdpClient.Client.LocalEndPoint).Port;
            Console.WriteLine(this.LocalPort.ToString());

            this.mUdpSender = new UDPSender(mUdpClient, endPoint);
            this.mUdpReceiver = new UDPReceiver(mUdpClient, endPoint);
        }

        /// <summary>
        /// Starts the UDP connection (sender and receiver).
        /// </summary>
        public void StartConnection()
        {
            IsConnected = true;
            mSenderThread = new Thread(new ThreadStart(this.mUdpSender.StartSending));
            mReceiverThread = new Thread(new ThreadStart(this.mUdpReceiver.StartReceiving));
            mSenderThread.Start();
            mReceiverThread.Start();
        }

        /// <summary>
        /// Stops the UDP connection (both the sender and the receiver).
        /// </summary>
        public void Disconnect()
        {
            Console.WriteLine("UDP DISCONNECTING!");
            this.IsConnected = false;
            if (this.mUdpClient != null)
                this.mUdpClient.Client.Close();
            this.mUdpClient = null;
        }
    }
}
